import React from "react"
import styled, { ThemeProvider } from "styled-components"
import Button from '@material-ui/core/Button';
import PropTypes from 'prop-types';
import CreateIcon from '@material-ui/icons/Create';
import GamepadIcon from '@material-ui/icons/Gamepad';
import PeopleOutline from '@material-ui/icons/PeopleOutline'
import {FetchAllDeviceList} from "../../actions/basicPrepareEquipmentManage.action"
import { initScene,
 
  addFloor,STOP,addCube,InstallImageFloor,
  installGuns,unInstallGuns,InstallLight,FunRotate,FunMove,
  AllowRotateObj,AllowMoveObj,LoadAllSpeaker,LoadAllArrivalCard,
  LoadAllRightPadArrivalCard,LoadAllLeftHardwareArrivalCard,
  LoadNames,
  LoadSeatsInfoEditor, UninstallHardwareStoreMenuOnScene,InstallHardwareStoreMenuOnScene,
  AttachechSpecifiedHardware,UnbindHardware,

}   from '../SceneActions';

import {BindSeatWithDevice} from "../../actions/seats.actions"
import * as _ from "lodash";
import DeleteIcon from '@material-ui/icons/Delete';
import FormatAlignLeft from "@material-ui/icons/FormatAlignLeft"
import RemoveCircle from "@material-ui/icons/RemoveCircle"
import VerticalAlignBottom from "@material-ui/icons/VerticalAlignBottom"
import Divider from '@material-ui/core/Divider';
import IconButton from '@material-ui/core/IconButton';
import { Menu, Icon, Switch } from 'antd';
// import { connect } from 'react-redux';
// import { bindActionCreators } from 'redux';
// import {  ShowVedio
// }   from '../scene/SceneActions';
// import Resizable from 're-resizable'
// import Card from '@material-ui/core/Card';
import ClearIcon from '@material-ui/icons/Clear';
import { withStyles } from '@material-ui/core/styles';
import TextField from '@material-ui/core/TextField';
import {BrowserView,
    MobileView,
    isBrowser,isMobile} from 'react-device-detect';
    import Draggable from 'react-draggable';
    import Paper from '@material-ui/core/Paper';
    import AppBar from '@material-ui/core/AppBar';
    import Tabs from '@material-ui/core/Tabs';
    import Tab from '@material-ui/core/Tab';
    // import Ai from './AI/Ai'
    import Typography from '@material-ui/core/Typography';
    const { SubMenu } = Menu;
// import { Menu } from "@material-ui/core";
    const MyForm= styled.form`
 
    position: absolute;
    width: 100px;
    height: 700px;
    top: 0px;
   
    ${(isMobile)?`left: 90px;`:`left:  90px;`}
    padding: 1px;
    background-color: #fff;
    color: white;

 `
 const styles = theme => ({
    root: {
      //  flexGrow: 1,
       top: 0,
       marginTop: 0,
      backgroundColor: theme.palette.background.paper,
      // height: 0,
      maxWidth: '100%',
      maxHeight:'100%'
    },
    container: {
   
     
      borderRadius : '5px',
      boxShadow: '5px 5px 5px #b2beb5' 
    },
    textField: {
      //  padding: '9.5px 14px'  ,
      marginLeft: theme.spacing.unit*0,
      marginRight: theme.spacing.unit*0,
    },
    button: {
      // marginLeft: '-15px' ,
        
      maxWidth: '20px',
       display:'block',
      // height: 34
    },
    dense: {
      marginTop: 0,
    },
    menu: {
      // width: 500,
    },
  });
 
  class HardwareStoreNav extends React.Component {
    constructor(props){
        super(props)
        this.state={
            activeDrags: 0,
            AllDeviceList:null,
            theme: 'dark',
            current: '1',
            treedata:[],
            currSelDeviceId: null,
            currSeatMapId: null, //当前坐席图id
            
        }
        this.myeditorRef = React.createRef()
 
        this.onStart=this.onStart.bind(this)
        this.onStop=this.onStop.bind(this)
    }
    componentDidMount(){
          //reactdom 调用工厂模式方法！！！
         //https://www.pluralsight.com/guides/different-ways-to-dispatch-actions-with-redux
         this.props.store.dispatch(FetchAllDeviceList())
    
    }
    
    static getDerivedStateFromProps(props, state) {
      if( props.store.getState().basicPrepareEquipmentManageReducer.AllDeviceList)
      if( state.AllDeviceList!==   props.store.getState().basicPrepareEquipmentManageReducer.AllDeviceList ){
          // this.lastPage()
          return {
            AllDeviceList:  props.store.getState().basicPrepareEquipmentManageReducer.AllDeviceList 
          }
      }
      return null;
    } 
    unbindDevice=( )=>{
      
       let currSelectedSeats = this.props.store.getState().seatReducer.SelectedSeats
       if(currSelectedSeats){
        this.props.store.dispatch(UnbindHardware(
          "解除坐席绑定的设备",this.state.currSelDeviceId, currSelectedSeats ))
       }
    }
     //是通过服务器端，更新reducer 后，通过reducer渲染到坐席图上，
    attachDeviceToSpecifedSeats=(deviceId, deviceName)=>{
      
             
        let currSelectedSeats = this.props.store.getState().seatReducer.SelectedSeats
        if(currSelectedSeats){
          //  alert(currSelectedSeats.length)
          //是不通过服务器端，更新reducer 后，通过reducer渲染到坐席图上，
            //因为当时接口还没做好   
               //  此时的通道号和地址号都是默认的0，因为还未指派
             let  passWayCode,CCUAddressCode =1
     
          
          //下面这是通过服务器
          let myjson=[]
          let one={}
          let hasBinded=false
          currSelectedSeats.map((obj,i)=>{
            hasBinded=false
            one.seatUnitId=obj.id
            // one.seatUnitId=currSelectedSeats[i].parent.id
            one.deviceUsedId=deviceId 
            //坐席图没有现成源码，全靠自己研发
            //搜集参数降低可扩张性，前端研发工作量大，怎么简单怎么来
            this.props.store.getState.seatReducer.SeatsMapBindDeviceMatrix.find((item, j)=>{
               if(one.seatUnitId===item.seatUnitId){
                
                 hasBinded=true
                 currSelectedSeats.splice(i,1)
                 return true
               }
            })
            if(!hasBinded){
               
               myjson.push(one)
            }
          })
          
          this.props.store.dispatch(BindSeatWithDevice(myjson)
          // .then((res)=>{
          //   this.props.store.dispatch(fetchSeatsListByDeviceIdAndSeatMapId( this.props.store.getState().seatReducer.seatMapId ,  this.state.currSelDeviceId))
          // })
          )
          this.props.store.dispatch(AttachechSpecifiedHardware("绑定设备到坐席",deviceId,passWayCode,CCUAddressCode ,currSelectedSeats))
      
          //
        }
      
    }
    formSubmenusChild=(obj)=>{
      let cHtml=<div></div>;
      let childArray=obj.children;
      if("undefined"!=typeof(childArray) && childArray.length>0) {
          cHtml = childArray.map((item, i) => {
              return this.formSubmenusChild(item);
          });
          return <SubMenu key={obj.id} title={obj.name} onTitleClick={this.onTitleClick1}>
            {/* {this.chooseIcon(obj.parentID)} */}
            {cHtml}</SubMenu>
      }else{
          return <Menu.Item 
          onClick={ (event)=>this.onTitleClick2(event,obj)}
          // routeurl={obj.routeurl} 
          // key={obj.id}><span>{this.chooseIcon(obj.parentID)}{obj.name}</span><button>编辑</button><button>编辑</button></Menu.Item>
          key={obj.id}><span >{this.chooseIcon(obj.parentID)}{obj.name}</span><button >编辑</button><button>编辑</button></Menu.Item>
      }
    }
    renderHardwareList=()=>{
        //childArray.map((item, i) => {})
        
        let html   
        
        if( this.props.store.getState().basicPrepareEquipmentManageReducer.AllDeviceList 
    && this.props.store.getState().basicPrepareEquipmentManageReducer.AllDeviceList.length>0
        ){
            html =  this.props.store.getState().basicPrepareEquipmentManageReducer.AllDeviceList[0].children.map((item,i)=>{
              return <Menu.Item   
                onClick={()=>{
                     
                     this.setState({
                      currSelDeviceId:item.devID
                     })
                       
                     this.attachDeviceToSpecifedSeats(item.devID,item.devName)
                }}
                key={item.devID} >
                  <div key={item.devID}>
                      <p style={{maxWidth:"150px",display:'flex',flexDirection:'row', wordBreak:'break-all'}}>
                        <span key={item.devID} >  {item.devID}</span>
                        <p key={item.devID} style={{maxWidth:"100px", width:"100px",wordWrap:"break-word" }}>  {item.devName}</p>
                      </p>
                      <p style={{maxWidth:"150px",display:'flex',flexDirection:'row', wordBreak:'break-all'}}>
                        ip地址:{item.devNetIPAddress}
                      </p>
                      <p style={{maxWidth:"150px",display:'flex',flexDirection:'row', wordBreak:'break-all'}}>
                        串口号:{item.devSerialPortCode}
                      </p>
                  </div>
                  

                {/* <span key={item.devID}>  {item.devName}</span> */}
              </Menu.Item>
          })
        }
        return html

    }
//     renderMenu=( )=>{
//       //https://www.jianshu.com/p/77e48c129c16
//       
//     let html = this.state.treedata.map((obj, i)=>{
//       if("undefined"!=typeof(obj.children) && obj.children.length>0){
//         return this.formSubmenusChild(obj);
//       } else {
//  /*        return <Menu.Item 
//         // routeurl={obj.routeurl} 
//       key={obj.id}><span>

//         {obj.name}</span></Menu.Item> */
//         return <SubMenu
//         // routeurl={obj.routeurl} 
//       key={obj.id} title={obj.name} onTitleClick={this.onTitleClick1}> </SubMenu>
//       }
//    })
     
//      return html
      
//   }
    onStart () {
        this.setState({activeDrags: ++this.state.activeDrags});
    } 
    onStop ()  {
        this.setState({activeDrags: --this.state.activeDrags});
    } 
    renderHardwareStore=()=>{

    }
    render(){
        const { classes } = this.props;
        const dragHandlers = {onStart: this.onStart, onStop: this.onStop};
        return (
            <Draggable handle="strong"  {...dragHandlers}  >
                <MyForm ref={this.myeditorRef} 
                  className={"resizableHardwareStore   no-cursor"} 
                  noValidate autoComplete="off" >
                    <div style={{display:'flex',flexDirection:'row'}}>
                    <strong className={"cursor"} style={{ width:'100%',height:'30px',display:'flex', flexDirection:'col'}}>
                   {/* 绑定设备到席位渲染关键是 AttachHardwareOneSeatOnly！！！ */}
                    关联设备 
                    </strong>
                    <DeleteIcon color={"secondary"} onClick={()=>{
                         this.unbindDevice()
                    }} />
                    </div>
                   
                    <Menu
                     theme={this.state.theme}
                     defaultOpenKeys={['sub2']}
                     mode="inline"
                    >
                      {this.renderHardwareList()}
                    </Menu>
                    
                </MyForm>
            </Draggable>
        )
    }
  }
   
  export default withStyles(styles, { withTheme: true })(HardwareStoreNav);
